package com.example.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.api.ResultUtil;
import com.example.common.filter.ReactiveRequestContextHolder;
import com.example.order.mapper.CartMapper;
import com.example.order.model.dto.CartDTO;
import com.example.order.model.po.CartPO;
import com.example.order.service.ICartService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartService extends ServiceImpl<CartMapper, CartPO> implements ICartService {

    @Resource
    private CartMapper cartMapper;

    @Override
    public Mono<ResultUtil> getCartById() {
        Mono<Long> requestMono = ReactiveRequestContextHolder.getUserId();
        return requestMono.flatMap(userId->{
            Map<String, Object> map = new HashMap<>();
            map.put("user_id", userId);
            List<CartPO> list = cartMapper.selectByMap(map);

            List<CartDTO> listDTO = list.stream().map(cartPO -> {
                CartDTO cartDTO = CartDTO.builder().build();
                BeanUtils.copyProperties(cartPO, cartDTO);
                return cartDTO;
            }).collect(Collectors.toList());

            return Mono.just(ResultUtil.success(listDTO));
        });
    }

    @Override
    public Mono<ResultUtil> getCartByPage(int pageIndex, int pageSize) {
        Mono<Long> requestMono = ReactiveRequestContextHolder.getUserId();
        return requestMono.flatMap(userId->{
            Page<CartPO> page = new Page<>(pageIndex, pageSize);
            QueryWrapper<CartPO> queryWrapper = new QueryWrapper<>();
            Map<String, Object> map = new HashMap<>();
            map.put("user_id", userId);
            queryWrapper.allEq(map);

            IPage<CartPO> iPage = cartMapper.selectPage(page, queryWrapper);

            IPage<CartDTO> iPageDTO = iPage.convert(cartPO -> {
                CartDTO cartDTO = CartDTO.builder().build();
                BeanUtils.copyProperties(cartPO, cartDTO);
                return cartDTO;
            });

            return Mono.just(ResultUtil.success(iPageDTO));
        });
    }

}
